import Taro from '@tarojs/taro'
import { View, Text, Input } from '@tarojs/components'
import { AtSearchBar, AtTabs, AtTabsPane, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtActivityIndicator } from 'taro-ui'
import dayjs from 'dayjs'

import { MemberList } from './memberList'
import { getMyMember, openMembership, getPrice } from '../../api/myMember'
import { showToast, getUpdatePage } from '../../utils'
import { ListLoading } from '../../components/loading'

import './index.less'

class MyMember extends Taro.Component {
  config = {
    navigationBarTitleText: '我的会员'
  }

  state = {
    current: 0,
    params: {
      vipStatus: '',
      pageSize: 12,
      pageNum: 1,
      key: 1,
      value: ''
    },
    memberList: [],
    payParams: {
      UserId: '',
      OrderPrice: ''
    },
    effectiveDate: '',
    isShowModal: false,
    isDone: false,
    priceInfo: {},
    isFocus: false
  }

  getMyMember = async () => {
    const res = await getMyMember(this.state.params)

    this.setState(({ memberList }) => ({
      memberList: memberList.concat(res.data)
    }), () => {
      if (this.state.memberList.length === res.rowCount) {
        this.setState({
          isDone: true
        })
      }
    })
  }

  componentDidMount() {
    this.setState({
      params: {
        ...this.state.params,
        value: this.$router.params.value
      }
    }, () => {
      this.getMyMember()
    })
  }

  componentDidShow() {
    getUpdatePage(() => {
      this.setState({
        memberList: [],
        isDone: false,
        params: {
          ...this.state.params,
          pageNum: 1
        }
      }, () => {
        this.getMyMember()
      })
    })
  }

  onReachBottom(){
    if (this.state.isDone) return

    const { pageNum } = this.state.params

    this.setState({
      params: {
        ...this.state.params,
        pageNum: pageNum + 1
      }
    }, () => {
      this.getMyMember()
    })
  }

  getVipStatus = val => {
    switch(val) {
      case 1:
        return 1
      case 2:
        return 0
      case 3:
        return 2
      default: 
        return ''
    }
  }

  handleClick = val => {
    this.setState({
      current: val,
      memberList: [],
      isDone: false,
      params: {
        ...this.state.params,
        pageNum: 1,
        vipStatus: this.getVipStatus(val)
      }
    }, () => {
      this.getMyMember()
    })
  }

  showModal = async (id, startDate) => {
    let res = {
      data: this.state.priceInfo
    }
    let effectiveDate = ''

    if (!res.data.price) res = await getPrice()

    if (startDate) {
      const nextDay = dayjs(startDate).add(1, 'days')
      effectiveDate = nextDay.format('YYYY.MM.DD') + '-' + nextDay.add(1, 'years').format('YYYY.MM.DD')
    } else {
      effectiveDate = dayjs().format('YYYY.MM.DD') + '-' + dayjs().add(1, 'years').format('YYYY.MM.DD')
    }

    this.setState({
      payParams: {
        UserId: id,
        OrderPrice: ''
      },
      effectiveDate,
      isShowModal: true,
      priceInfo: res.data
    })
  }

  pay = async () => {
    if (this.state.payParams.OrderPrice === '') {
      showToast('请填写收款金额')

      return
    }

    Taro.showLoading()

    const res = await openMembership(this.state.payParams)

    Taro.hideLoading()

    if (res.code === 1) {
      showToast('开通成功！')

      const { memberList, payParams, effectiveDate } = this.state
      
      for (let item of memberList) {
        if (item.id === payParams.UserId) {
          item.status = 1
          item.expiredTime = effectiveDate.split('-')[1]

          this.setState({ memberList })

          break
        }
      }
      
      this.setState({
        isShowModal: false,
        payParams: {
          UserId: '',
          OrderPrice: ''
        }
      })
    } else {
      showToast(res.message)
      
      this.setState({
        isShowModal: false,
        payParams: {
          UserId: '',
          OrderPrice: ''
        }
      })
    }
  }

  onModalClose = () => {
    this.setState({
      isShowModal: false
    })
  }

  handleInput = ev => {
    this.setState({
      payParams: {
        ...this.state.payParams,
        OrderPrice: ev.target.value
      }
    })
  }

  toSearch = () => {
    if (!this.state.params.value) {
      showToast('请输入要搜索的内容！')

      return
    }

    if (this.$router.params.value) {
      this.setState({
        memberList: [],
        isDone: false,
        params: {
          ...this.state.params,
          pageNum: 1
        },
      }, () => {
        this.getMyMember()
      })
    } else {
      Taro.navigateTo({
        url: 'index?value=' + this.state.params.value
      })
  
      this.setState({
        params: {
          ...this.state.params,
          value: ''
        }
      })
    }
  }

  handleChange = val => {
    this.setState({
      params: {
        ...this.state.params,
        value: val.trim()
      }
    })
  }

  render() {
    const tabList = [{ title: '全部' }, { title: 'VIP' }, { title: '未开通' }, { title: '已过期' }]
    const { current, memberList, isShowModal, params, payParams, isDone, priceInfo, effectiveDate, isFocus } = this.state

    return (
      <View className="page" style={{ paddingBottom: '48Px' }}>
        <AtSearchBar
          placeholder="搜索会员姓名/手机号"
          value={ params.value }
          onChange={ this.handleChange }
          onActionClick={ this.toSearch }
          onFocus={ () => this.setState({ isFocus: true }) }
          onBlur={ () => this.setState({ isFocus: false }) }
          onConfirm={ this.toSearch }
        />
        {
          isFocus
          ? <View className="search-mask" />
          : null
        }
        <AtTabs
          current={ current }
          tabList={ tabList }
          onClick={ this.handleClick }
        >
          <AtTabsPane current={ current } index={ 0 }>
            <MemberList data={ memberList } showModal= { this.showModal } />
          </AtTabsPane>
          <AtTabsPane current={ current } index={ 1 }>
            <MemberList data={ memberList } showModal= { this.showModal } />
          </AtTabsPane>
          <AtTabsPane current={ current } index={ 2 }>
            <MemberList data={ memberList } showModal= { this.showModal } />
          </AtTabsPane>
          <AtTabsPane current={ current } index={ 3 }>
            <MemberList data={ memberList } showModal= { this.showModal } />
          </AtTabsPane>
        </AtTabs>
        <ListLoading isDone={ isDone } data={ memberList } />
        <AtModal isOpened={ isShowModal } onClose={ this.onModalClose }>
          <AtModalHeader>希朗AI课堂1年会员</AtModalHeader>
          <AtModalContent>
            <View className="modal-content">
              <Text>有效期：{ effectiveDate }</Text>
              <Text>原价：{ priceInfo.price } 折扣价：{ priceInfo.priceDiscount }</Text>
            </View>
            <View className="modal-input">
              <Text>实际收款：</Text><Input type="number" value={ payParams.OrderPrice } onInput={ this.handleInput } />
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button onClick={ this.pay }>确定</Button>
          </AtModalAction>
        </AtModal>
        <Navigator url="addMember" className="add-btn">新增</Navigator>
      </View>
    )
  }
}

export default MyMember